package com.EventHandler;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.Dao.NewsDao;
import com.Dao.UserDao;
import com.example.myapplication.PostNewsActivity;
import com.example.myapplication.R;
import com.news.model.News;

/*
* 处理事件 --点击事件、分类资源加载等等
* */
public class PostEventHandler {
    private Button postnewsbtn;  //提交新闻按钮
    private NewsDao newsDao;
    private UserDao userDao;
    private Context context;
    private News news;
    private View view;
    private int userid;
    private String username;
    //构造函数
    public PostEventHandler(Context context){
        //创建 PostEventHandler 类的实例时，初始化该类中的成员变量
        this.context = context;
        userDao = new UserDao(context);
        newsDao = new NewsDao(context);
    }
    //初始化控件
    public void initializeUI(){
        //从名为PostNewsActivity的Activity类中的实例context中
        //寻找Id为R.id.submitButton的按钮，并赋值给postnewsbtn
        postnewsbtn = ((PostNewsActivity)context).findViewById(R.id.submitButton);
        //获取一个名为user_info的SharedPreferences实例
        SharedPreferences sharedPreferences = context.getSharedPreferences("user_info", Context.MODE_PRIVATE);
        //获取用户名
        username = sharedPreferences.getString("username",null);
    }
    //设置监听器
    public void setListeners(){
        //提交新闻按钮 监听器
        postnewsbtn.setOnClickListener(new View.OnClickListener() {
            //点击后检查
            @Override
            public void onClick(View v) {
                //获取数据view
                EditText titleview = (EditText) ((PostNewsActivity)context).findViewById(R.id.titleEditText);
                EditText contentview = (EditText)((PostNewsActivity)context).findViewById(R.id.contentEditText);
                Spinner spinner = (Spinner)((PostNewsActivity)context).findViewById(R.id.categorySpinner);
                //转成字符串
                String title = titleview.getText().toString();
                String content = contentview.getText().toString();
                String category = spinner.getSelectedItem().toString();
                long currentTime = System.currentTimeMillis();
                Log.i("分类",category);
                //检查格式
                if(check(title,content,category)){
                    news = new News(title,content,category,username,currentTime,null);
                    handlesubmit(news);
                }
            }
        });
    }
    //提交按钮事件
    public void handlesubmit(News news){
        long flag = newsDao.insertNews(news);
        if(flag!=-1){
            Log.i("database","新闻插入成功");
            Toast.makeText(context, "新闻插入成功！", Toast.LENGTH_SHORT).show();
        }

    }
    public boolean check(String title,String content,String category){return true;}
}
